const puppeteer = require('puppeteer');

(async () => {
	let browser = await puppeteer.launch();
	let page = await browser.newPage();
	let url = `https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20`;

	await page.goto(url, {
		wainUntil: ['networkidle0']
	});

	await sleep(3000);
	// await page.screenshot({path: 'example.png'});
	// await page.pdf({path: 'hn.pdf', format: 'A4'});

	await page.waitForSelector('.more');

	// 点击事件循环点击一次
	for (let i = 0; i < 1; i++) {
		await page.click('.more');
		await sleep(3000);
	}


	let result = await page.evaluate(() => {
		let $ = window.$;
		let items = $('.item');
		let links = [];

		if (items.length > 0) {
			items.each((index, item) => {
				let it = $(item);
				let movieId = it.find('div').data('id');
				let title = it.find('img').attr('alt');
				let rate = Number.parseInt(it.find('strong').text());
				let poster = String(it.find('img').attr('src')).replace('s_ratio', 'l_ratio');

				links.push({
					movieId,
					title,
					rate,
					poster
				});
			});
		}
		return links;
	});

	browser.close();
	process.send(result);
	process.exit(0);
})();

const sleep = time => new Promise((resolve, reject) => {
	setTimeout(resolve, time);
});